<template>
  <div class="app-container">
    <!-- 查询条件区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="月份" prop="month">
        <el-date-picker
          v-model="queryParams.month"
          type="month"
          value-format="YYYY-MM"
          placeholder="请选择月份"
          style="width: 240px"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="部门" prop="departmentName">
        <el-select
          v-model="queryParams.departmentName"
          placeholder="请选择部门"
          clearable
          style="width: 240px"
        >
          <el-option v-for="dept in departments" :key="dept.value" :label="dept.label" :value="dept.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="提案人" prop="proposerName">
        <el-input
          v-model="queryParams.proposerName"
          placeholder="请输入提案人姓名"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="填写状态" prop="savingStatus">
        <el-select
          v-model="queryParams.savingStatus"
          placeholder="请选择填写状态"
          clearable
          style="width: 240px"
        >
          <el-option label="已填写" value="filled"></el-option>
          <el-option label="未填写" value="unfilled"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 提案数据表格 -->
    <el-table v-loading="loading" :data="proposalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="部门" align="center" prop="departmentName" :show-overflow-tooltip="true" />
      <el-table-column label="月份" align="center" prop="month" width="100" />
      <el-table-column label="提案人" align="center" prop="proposerName" width="100" />
      <el-table-column label="提案名称" align="center" prop="title" :show-overflow-tooltip="true" />
      
      <!-- 图片显示列 -->
      <el-table-column label="图片" align="center" width="120">
        <template #default="scope">
          <div v-if="scope.row.image">
            <!-- 处理多个图片的情况 -->
            <div v-if="scope.row.image.includes(',')">
              <!-- 折叠/展开按钮 -->
              <div class="image-toggle" @click="toggleImageList(scope.row)">
                <span v-if="!scope.row.showAllImages">展开全部图片 ({{ scope.row.image.split(',').length }})</span>
                <span v-else>收起图片</span>
                <el-icon :class="{ 'rotate': scope.row.showAllImages }">
                  <arrow-down />
                </el-icon>
              </div>
              
              <!-- 图片列表（可折叠） -->
              <div v-show="scope.row.showAllImages" class="image-list">
                <div v-for="(img, index) in scope.row.image.split(',')" :key="index" style="margin-bottom: 5px;">
                  <el-link 
                    :href="getImageUrl(img)" 
                    target="_blank" 
                    type="primary"
                    :underline="false">
                    图片 {{ index + 1 }}
                  </el-link>
                </div>
              </div>
            </div>
            <!-- 单张图片的情况 -->
            <div v-else>
              <el-link 
                :href="getImageUrl(scope.row.image)" 
                target="_blank" 
                type="primary"
                :underline="false">
                查看图片
              </el-link>
            </div>
          </div>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      
      <el-table-column label="一次性节省金额" width="150">
        <template #default="scope">
          <el-input 
            v-model="scope.row.oneTimeSaving" 
            @blur="handleSavingsChange(scope.row)"
            @input="formatInput(scope.row, 'oneTimeSaving')">
          </el-input>
        </template>
      </el-table-column>
      <el-table-column label="持续节省金额" width="150">
        <template #default="scope">
          <el-input 
            v-model="scope.row.monthlySaving" 
            @blur="handleSavingsChange(scope.row)"
            @input="formatInput(scope.row, 'monthlySaving')">
          </el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['proposal:finance:edit']">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup name="ProposalFinance">
// 引入相关依赖
import { listFinanceProposals, updateFinanceSavings } from "@/api/ciinput/proposal";
import { departments, getImageUrl } from '@/utils/proposalData';

const { proxy } = getCurrentInstance();
const baseUrl = import.meta.env.VITE_APP_BASE_API;

// 定义响应式数据
const proposalList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 定义查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  month: undefined,
  departmentName: undefined,
  proposerName: undefined,
  savingStatus: 'unfilled' // 默认加载未填写节省金额的数据
});



// 切换图片列表显示状态
function toggleImageList(row) {
  // 如果是第一次点击，初始化showAllImages属性
  if (!row.hasOwnProperty('showAllImages')) {
    row.showAllImages = false;
  }
  
  // 切换显示状态
  row.showAllImages = !row.showAllImages;
}

// 格式化输入值，保留两位小数
function formatInput(row, field) {
  let value = row[field];
  if (value !== null && value !== undefined && value !== '') {
    // 移除非数字和小数点以外的字符
    value = value.toString().replace(/[^\d.]/g, '');
    // 保留两位小数
    const parts = value.split('.');
    if (parts.length > 1) {
      value = parts[0] + '.' + parts[1].substring(0, 2);
    }
    row[field] = value;
  }
}

/** 查询提案列表 */
function getList() {
  loading.value = true;
  listFinanceProposals(queryParams.value).then(response => {
    
    proposalList.value = response.rows || [];
    total.value = response.total || 0;

    
    // 处理数据字段映射和格式化
    proposalList.value.forEach(row => {
      // 处理节省金额字段，确保正确显示数据库中的值
      // 如果数据库中有值则显示，否则显示为空
      if (row.oneTimeSaving !== undefined && row.oneTimeSaving !== null) {
        if (row.oneTimeSaving !== '') {
          // 确保数值被正确格式化为字符串并保留两位小数
          row.oneTimeSaving = parseFloat(row.oneTimeSaving).toFixed(2);
        } else {
          row.oneTimeSaving = '';
        }
      } else {
        row.oneTimeSaving = '';
      }
      
      if (row.monthlySaving !== undefined && row.monthlySaving !== null) {
        if (row.monthlySaving !== '') {
          // 确保数值被正确格式化为字符串并保留两位小数
          row.monthlySaving = parseFloat(row.monthlySaving).toFixed(2);
        } else {
          row.monthlySaving = '';
        }
      } else {
        row.monthlySaving = '';
      }
      
      // 处理图片字段 - 确保兼容不同的图片字段名
      if ((row.image === undefined || row.image === null) && row.img !== undefined) {
        row.image = row.img;
      }
      
      // 为每行数据添加showAllImages属性，初始值为false
      if (row.image && typeof row.image === 'string' && row.image.includes(',')) {
        row.showAllImages = false;
      }
    });
    
    loading.value = false;
  }).catch((error) => {
    console.error('获取提案列表失败:', error);
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
  console.log('查询参数:', queryParams.value);
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.savingStatus = 'unfilled';
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const id = row.id || ids.value[0];
  proxy.$modal.msgInfo("请直接在表格中修改节省金额");
}

/** 处理节省金额变更 */
function handleSavingsChange(row) {
  // 确保传递给后端的是正确字段名和数值类型
  const data = {
    id: row.id,
    oneTimeSaving: row.oneTimeSaving !== '' && row.oneTimeSaving !== null ? Number(row.oneTimeSaving) : null,
    monthlySaving: row.monthlySaving !== '' && row.monthlySaving !== null ? Number(row.monthlySaving) : null
  };
  
  updateFinanceSavings(data).then(response => {
    proxy.$modal.msgSuccess("节省金额更新成功");
    // 更新成功后重新格式化显示值
    row.oneTimeSaving = data.oneTimeSaving !== null ? Number(data.oneTimeSaving).toFixed(2) : '';
    row.monthlySaving = data.monthlySaving !== null ? Number(data.monthlySaving).toFixed(2) : '';
  }).catch(() => {
    proxy.$modal.msgError("节省金额更新失败");
  });
}

/** 页面加载时获取数据 */
getList();
</script>

<style scoped>
.image-toggle {
  cursor: pointer;
  color: #409eff;
  font-size: 12px;
  padding: 2px 0;
  display: flex;
  align-items: center;
  gap: 4px;
}

.image-toggle:hover {
  text-decoration: underline;
}

.rotate {
  transform: rotate(180deg);
}

.image-list {
  margin-top: 8px;
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 8px;
  background-color: #f5f7fa;
}

.image-list::-webkit-scrollbar {
  width: 6px;
}

.image-list::-webkit-scrollbar-track {
  background: #f5f7fa;
  border-radius: 3px;
}

.image-list::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.image-list::-webkit-scrollbar-thumb:hover {
  background: #909399;
}
</style>